package sms

import (
	"awesomeProject1/push/plugin"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"log"
)

// AliSmsService 是阿里云短信服务的实现
type AliSmsService struct {
	AccessKeyID     string
	AccessKeySecret string
	SignName        string
	TemplateCode    string
}

// NewAliSmsService 创建一个新的 AliSmsService 实例
func NewAliSmsService(accessKeyID, accessKeySecret, signName, templateCode string) *AliSmsService {
	return &AliSmsService{
		AccessKeyID:     accessKeyID,
		AccessKeySecret: accessKeySecret,
		SignName:        signName,
		TemplateCode:    templateCode,
	}
}

// SendSMS 实现了 SmsService 接口的 SendSMS 方法
func (s *AliSmsService) SendSMS(info plugin.MessageInfo) error {
	client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", s.AccessKeyID, s.AccessKeySecret)
	if err != nil {
		log.Println("=======================>sms连接出现错误", err)
		return nil // 不要影响程序主业务 有err也不抛出
	}
	log.Println("=======================>sms连接配置信息", client)

	request := requests.NewCommonRequest()               // 构造一个公共请求
	request.Method = "POST"                              // 设置请求方式
	request.Product = "Ecs"                              // 指定产品
	request.Scheme = "http"                              // https | http
	request.Domain = "dysmsapi.aliyuncs.com"             // 指定域名则不会寻址，如认证方式为 Bearer Token 的服务则需要指定
	request.Version = "2017-05-25"                       // 指定产品版本
	request.ApiName = "SendSms"                          // 指定接口名
	request.QueryParams["RegionId"] = "cn-hangzhou"      // 地区
	request.QueryParams["SignName"] = s.SignName         //阿里云验证过的项目名
	request.QueryParams["TemplateCode"] = s.TemplateCode //阿里云的短信模板号
	//request.QueryParams["TemplateParam"] = "{\"code\":" + info.Message + "}" //短信模板中的信息内容
	var code = "1234"
	request.QueryParams["TemplateParam"] = "{\"code\":" + code + "}"

	// 批量发送
	for i := 0; i < len(info.Receiver); i++ {
		request.QueryParams["PhoneNumbers"] = info.Receiver[i] //手机号
		response, err := client.ProcessCommonRequest(request)
		if err != nil {
			log.Println("=======================>发送短信有错误", err)
			continue
		}
		log.Println("=======================>信息发送响应", response.String())
		log.Println("=======================>信息发送完毕", i)
	}
	return nil // 不要影响程序主业务 有err也不抛出
}
